package net.zjitc.security;

import net.zjitc.entity.Manager;
import net.zjitc.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 毛钰深
 * @create 2022/1/25
 */
@Service
//实现从数据库中查询用户名和密码,并返回UserDetails对象(需要配置到security中)
public class IUserDetailService implements UserDetailsService {

    @Autowired
    private ManagerService managerService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //返回UserDetails这个对象,security内部会封装,然后和来身份认证的登录信息进行对比,如果相匹配就登录
        //该service查询相关的manger信息并且封装到UserDetails的子类中,再返回
        Manager manager = managerService.getByUsername(username);

        //没有查到该用户
        if (manager==null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        return new AccountUserDetails(
                manager.getId(),
                manager.getUsername(),
                manager.getPassword(),
                getUserAuthority(manager)
        );
    }

    /**
     * 获取用户的(角色,菜单权限)
     * @param manager
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Manager manager){

        //角色(ROLE_admin),菜单(ps_id)操作权限
        //返回一个逗号分隔的字符串,包含这些权限
        String authority = managerService.getUserAuthirutyInfo(manager);
        //工具类将字符串转换为List<GrantedAuthority>的权限集合
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
